package org.wanxian.stores.db;

import java.util.ArrayList;

import org.wanxian.stores.model.ProductInIndent;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ProductInIndentDao {
	
	
	private DatabaseOpenHelper dbHelper;
	private static final String TABLE_NAME = "prodeuctInIndent";
	
	public ProductInIndentDao(Context context) {
		dbHelper = new DatabaseOpenHelper(context);
	}
	
	public int insert(ProductInIndent productInIndent) {
		ProductInIndent bef = queryById(productInIndent.getId());
		if(bef != null) {
			deleteById(bef.getId());
		}
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("indentId", productInIndent.getIndentId());
		values.put("productId", productInIndent.getProductId());
		values.put("num", productInIndent.getNum());
		int id = (int) db.insert(TABLE_NAME, null, values);
		return id;
	}
	
	public int update(ProductInIndent productInIndent) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues value = new ContentValues();
		value.put("indentId", productInIndent.getIndentId());
		value.put("productId", productInIndent.getProductId());
		value.put("num", productInIndent.getNum());
		int index = (int) db.update(TABLE_NAME, value, "id = ?", new String[]{String.valueOf(productInIndent.getId())});
		db.close();
		return index;
	}
	
	public void deleteById(int id) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(TABLE_NAME, "id = ?", new String[] {String.valueOf(id)});
		db.close();
	}
	
	public ProductInIndent queryById(int id) {
		ProductInIndent product = null;
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		Cursor cursor = db.query(TABLE_NAME, null, "id = ?", new String[]{String.valueOf(id)}, null, null, null);
		while(cursor.moveToNext()) {
			int indentId = cursor.getInt(cursor.getColumnIndex("indentId"));
			int productId = cursor.getInt(cursor.getColumnIndex("productId"));
			int num = cursor.getInt(cursor.getColumnIndex("num"));
			product = new ProductInIndent(id, indentId, productId, num);
		}
		cursor.close();
		db.close();
		return product;
	}
	
	public ArrayList<ProductInIndent> queryAllByIndentId(int indentId) {
		ArrayList<ProductInIndent> list = new ArrayList<ProductInIndent>();
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		Cursor cursor = db.query(TABLE_NAME, null, "indentId = ?", new String[]{String.valueOf(indentId)}, null, null, null);
		while(cursor.moveToNext()) {
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			int productId = cursor.getInt(cursor.getColumnIndex("productId"));
			int num = cursor.getInt(cursor.getColumnIndex("num"));
			ProductInIndent productInIndent = new ProductInIndent(id, indentId, productId, num);
			list.add(productInIndent);
		}
		cursor.close();
		db.close();
		return list;
	}
}
